package com.ruoyi.activiti.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.AjaxPageResult;
import com.ruoyi.common.core.web.page.PageDomain;
import com.ruoyi.common.core.web.page.TableSupport;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static org.activiti.editor.constants.ModelDataJsonConstants.MODEL_DESCRIPTION;
import static org.activiti.editor.constants.ModelDataJsonConstants.MODEL_NAME;

/**
 * 流程模型控制层
 *
 * @author scihi
 */
@RestController
@RequestMapping("/activiti/modeler")
@Api(tags="流程图")
@Validated//有此注解，才会校验游离的参数
@Slf4j
public class ModelerController extends BaseController {

    @Autowired
    private RepositoryService repositoryService;

    @ApiOperation(value = "查询流程图列表", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "流程图名字，模糊匹配", paramType = "form")
            , @ApiImplicitParam(name = "key", value = "流程图key", paramType = "form")
    })
    @GetMapping("/list")
    public AjaxPageResult list(String key, String name) {
        ModelQuery modelQuery = repositoryService.createModelQuery();
        modelQuery.orderByCreateTime().desc();
        // 条件过滤
        if (StringUtils.isNotBlank(key)) {
            modelQuery.modelKey(key);
        }
        if (StringUtils.isNotBlank(name)) {
            modelQuery.modelNameLike(name + "%");
        }
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        List<Model> resultList = modelQuery.listPage((pageNum - 1) * pageSize, pageSize);
        /*Page<ModelEntityImpl> page = new Page<>();
        resultList.parallelStream().forEach(model -> {
            ModelEntityImpl modelEntity1 = (ModelEntityImpl) model;
            page.add(modelEntity1);
        });*/
        return AjaxPageResult.success(resultList).setTotal(modelQuery.count());
    }

    @ApiOperation(value = "查询流程图", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "modelId", value = "流程图id", paramType = "path")
    })
    @GetMapping("/{modelId}")
    public AjaxResult list(@PathVariable String modelId) {
        ModelQuery modelQuery = repositoryService.createModelQuery()
                .modelId(modelId);
        Model model = modelQuery.singleResult();
        return AjaxResult.success(model);
    }

    @ApiOperation(value = "创建空的流程图", notes = "", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "流程图名字", required = true, paramType = "form")
            , @ApiImplicitParam(name = "key", value = "流程图key", required = true, paramType = "form")
            , @ApiImplicitParam(name = "description", value = "描述", paramType = "form")
    })
    @PostMapping(value = "/create")
    public AjaxResult create(@NotBlank String name, @NotBlank String key, String description) {
        try {
            long count = repositoryService.createModelQuery()
                    .modelKey(key)
                    .count();
            if(count>0){
                return AjaxResult.error("流程图key重复");
            }
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(MODEL_NAME, name);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            description = StringUtils.defaultString(description);
            modelObjectNode.put(MODEL_DESCRIPTION, description);

            Model newModel = repositoryService.newModel();
            newModel.setMetaInfo(modelObjectNode.toString());
            newModel.setName(name);
            newModel.setKey(StringUtils.defaultString(key));
            newModel.setCategory("默认分组");

            repositoryService.saveModel(newModel);
            repositoryService.addModelEditorSource(newModel.getId(), editorNode.toString().getBytes(StandardCharsets.UTF_8));

            return AjaxResult.success().setMsg("创建模型成功").setData(newModel.getId());
        } catch (Exception e) {
            logger.error("创建模型失败：", e);
        }
        return error();
    }

    @ApiOperation(value = "部署流程图", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "modelId", value = "流程图id", paramType = "path", required = true)
    })
    @Transactional
    @PostMapping(value = "/deploy/{modelId}")
    @ResponseBody
    public AjaxResult deploy(@PathVariable("modelId") String modelId) {
        try {
            Model modelData = repositoryService.getModel(modelId);
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));

            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model);

            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment()
                    .name(modelData.getName())
                    .key(modelData.getKey())
                    .category("默认部署分组")
                    .addString(processName, new String(bpmnBytes, "UTF-8")).deploy();
            log.info("部署成功，部署ID=" + deployment.getId());
            return AjaxResult.success().setMsg("部署成功");
        } catch (Exception e) {
            log.error("根据模型部署流程失败：modelId={}", modelId, e);
        }
        return error("部署失败");
    }

    @ApiOperation(value = "导出流程图xml", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "modelId", value = "流程图id", paramType = "path", required = true)
    })
    @GetMapping(value = "/export/{modelId}")
    public void export(@PathVariable("modelId") String modelId, HttpServletResponse response) {
        try {
            Model modelData = repositoryService.getModel(modelId);
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            JsonNode editorNode = new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);

            // 流程非空判断
            if (!CollectionUtils.isEmpty(bpmnModel.getProcesses())) {
                BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
                byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel);

                ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);
                String filename = bpmnModel.getMainProcess().getId() + ".bpmn";
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);
                IOUtils.copy(in, response.getOutputStream());
                response.flushBuffer();
            }

        } catch (Exception e) {
            log.error("导出model的xml文件失败：modelId={}", modelId, e);
        }
    }

    @ApiOperation(value = "删除流程图", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "流程图ids，多个用逗号隔开", paramType = "path", required = true)
    })
    @Log(title = "流程模型", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{ids}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("ids") String ids) {
        for (String s : ids.split(",")) {
            repositoryService.deleteModel(s);
        }
        return AjaxResult.success();
    }
}
